package br.ufc.great;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class JsonThread extends Thread {

	Handler handler;
	String login, password;
	float latitude, longitude;	
	public JsonThread(Handler h, String login, int latitude, int longitude) {
		this.handler = h;
		this.login = login;
		this.latitude = (float) (latitude/1E6);
		this.longitude = (float) (longitude/1E6);
	}

	public void run() {
		HttpClient httpClient = new DefaultHttpClient();

		String key = "AIzaSyBqS3em8XuCJqlqWcICSvEw929_bt1fyyw";
		//String latitude = "-3.75001";
		//String longitude = "-38.57692";
		System.out.println(latitude + " / " + longitude);
		String url = "https://maps.googleapis.com/maps/api/place/search/json?location="
				+ latitude
				+ ","
				+ longitude
				+ "&radius=2000&sensor=false&key=" + key;

		JSONObject jsonObject = getJSONfromURL(url);

		Log.d("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk",
				jsonObject.toString());

		List<String> names = new ArrayList<String>();
		List<String> locations = new ArrayList<String>();
		JSONArray jsonArray = null;
		try {

			jsonArray = (JSONArray) jsonObject.get("results");

		} catch (JSONException e) {
			e.printStackTrace();
		}


		if (jsonArray != null) {
			for (int i = 0; i < jsonArray.length(); i++) {
				try {
					names.add(jsonArray.getJSONObject(i).getString("name"));
					
					double latTemp = jsonArray.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
					double lngTemp = jsonArray.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng"); 

					locations.add(latTemp + "," + lngTemp);
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		}

		Message m = handler.obtainMessage();
		Bundle b = new Bundle();

		String[] namesString = new String[names.size()];
		String[] locationsString = new String[locations.size()];
		
		for (int i=0; i<names.size(); i++) {
			namesString[i] = names.get(i);
			System.out.println(names.get(i));
			locationsString[i] = locations.get(i);
			System.out.println(locations.get(i));
		}

		b.putStringArray("names", namesString);
		b.putStringArray("locales", locationsString);
		// b.putString("response", namesString);

		m.setData(b);

		handler.sendMessage(m);
	}

	public static JSONObject getJSONfromURL(String url) {

		// initialize
		InputStream is = null;
		String result = "";
		JSONObject jArray = null;

		// http post
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(url);
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();

		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		// convert response to string
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "iso-8859-1"), 8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("log_tag", "Error converting result " + e.toString());
		}

		// try parse the string to a JSON object
		try {
			jArray = new JSONObject(result);
		} catch (JSONException e) {
			Log.e("log_tag", "Error parsing data " + e.toString());
		}

		return jArray;
	}

}
